package com.tripshare.sdk.weixin.api.util;

import com.google.gson.Gson;
import com.thoughtworks.xstream.XStream;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class XmlUtil {

    private static final XStream xstream = new XStream();

    private static final Gson gson = JsonUtil.gson;

    static {
        xstream.alias("xml", Map.class);
        xstream.registerConverter(new XmlConverter());
        xstream.ignoreUnknownElements();
    }

    public static String objectToXml(Object object) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        String s = gson.toJson(object);
        Map map = gson.fromJson(s, Map.class);

        Map mm = new HashMap();
        mm.putAll(map);
        return xstream.toXML(mm);
    }

    public static <T> T xmlToObject(String xml, Class<T> type) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        Object o = xstream.fromXML(xml);
        return gson.fromJson(gson.toJson(o), type);
    }

}
